let db = require("../db/db")

let handle = async function (action, data, login_info, req, res) {
	let username = data.username;
	switch (action) {
		case "in":
			let password = data.password;
			let sql = "select * from sys_user where `username`=? and `password`=?";
			let result = await db.query(sql, [username, password]);
			let rows = result.rows;
			if (rows.length == 0) {
				return { success: false, msg: '错误的用户名或密码' };
			}
			else {
				let user_id = rows[0].id;
				let emp_id = rows[0].emp_id;
				let index_page = rows[0].index_page;
				//建session
				let token = guid();
				//查员工信息
				let sql = "select e.name as emp_name,e.job_number as job_number,o.id as org_id,o.name as org_name from ehr_employee e left outer join ehr_org o on e.org_id=o.id where e.id=?";
				let result = await db.query(sql, [emp_id]);
				if (result.rows.length == 0) { throw Error("未找到员工信息"); return; }
				let position_id="";
				let position_name="";
				sql = "select * from ehr_empolyee_position_r r left outer join ehr_position p on r.position_id=p.id where r.employee_id=? order by r.position_type";
				let p_result = await db.query(sql, [emp_id]);
				let positions = p_result.rows;
				if(positions.length>0){
					position_id=positions[0].id;
					position_name=positions[0].name;
				}

				let row = result.rows[0];
				let info = {
					username: username,
					user_id: user_id,
					emp_id: emp_id,
					emp_name: row.emp_name,
					org_id: row.org_id,
					org_name: row.org_name,
					position_id: position_id,
					position_name: position_name,
					job_number: row.job_number,
					ip: req.ip
				}
				let login_time = new Date(new Date().getTime() + 1000 * 60 * 60 * 8);
				let expire_time = new Date(login_time.getTime() + 1000 * 60 * 20);
				sql = "insert into sys_session set ?";
				let params = {
					token: token,
					info: JSON.stringify(info),
					login_time: login_time,
					expire_time: expire_time,
					create_user: user_id
				}
				await db.add(sql, params);
				res.cookie("token", token);
				res.cookie("user_id", user_id);
				res.cookie("username", username);
				res.cookie("index_page", index_page);
				res.cookie("emp_id", emp_id);
				res.cookie("emp_name", row.emp_name);
				res.cookie("org_id", row.org_id);
				res.cookie("org_name", row.org_name);
				res.cookie("position_id", position_id);
				res.cookie("position_name", position_name);
				res.cookie("job_number", row.job_number);
				return { success: true };
			}
			break;
		case "out":
			//清session
			res.clearCookie("token");
			res.clearCookie("username");
			return { success: true };
			break;
		default:
			throw Error('未知的action:' + action);
	}
}

//check session，update session
let get_refresh_login_info = async function (token) {
	let sql = "select * from sys_session where token=? and expire_time>=? and is_deleted=0";
	let result = await db.query(sql, [token, new Date(new Date().getTime() + 1000 * 60 * 60 * 8)]);
	let rows = result.rows;
	if (rows.length == 0) {
		throw Error("登录已过期");
	}
	else {
		let log_info = JSON.parse(rows[0].info);
		let user_id = log_info.user_id;
		let expire_time = new Date(new Date().getTime() + 1000 * 60 * 60 * 8 + 1000 * 60 * 20);
		let sql = "update sys_session set expire_time=?,update_user=? where token=? and is_deleted=0";
		await db.update(sql, [expire_time, user_id, token]);
		return log_info;
	}
}

function guid() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
}

module.exports = { handle, get_refresh_login_info };